import jwt from 'jsonwebtoken';
import {config} from "../config/portConfig.js";
import {httpResult} from "../utils/utils.js";

let jwtKey = config.jwtKey;
// 不需要权限校验的请求
const non_auth_req = {
  '/user/signin': true,
  '/user/login': true,
  '/user/getinfolist': true,
  '/test': true
};

export const authToken = async (req, res, next) => {
  console.log(1);
  if (req.method === 'OPTIONS') {
    next();
    return;
  }
  if (non_auth_req[req.url]) {
    next();
    return;
  }
  if (!req.headers['authorization']) return;
  const token = req.headers['authorization'].split(" ")[1];
  let sender = req.headers['authorization'].split(" ")[2];
  const tokenResult = await verifyToken(token, sender);

  if (!tokenResult) {
    throw new Error("请重新登录账号。");
    return;
  }
  next();
};
export const createToken = (account) => {
  return new Promise((resolve, reject) => {
    jwt.sign(
      {account},
      jwtKey,
      {expiresIn: "72h"},
      (err, token) => {
        if (err) {
          reject(err);
        }
        resolve(token);
      }
    );
  });
};
const verifyToken = async (token, sender) => {
  return new Promise((resolve, reject) => {
    jwt.verify(token, jwtKey, (err, decoded) => {
      if (err || decoded.account !== sender) {
        resolve(false);
      } else {
        resolve(true);
      }
    });
  });

};
